<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>中奖记录</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css">
    <link rel="stylesheet" href="./css/base.css">
    </link>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 0 30px;
        }

        table {
            /* height: calc(100vh - 143px); */
            height: 300px;
        }

        .table td,
        .table th {
            border: none;
        }

        .table thead th {
            background-color: #f7f7f7;
            border-bottom: none;
            font-weight: 600;
            font-size: 16px;
            color: #999999;
            height: 80px;
            line-height: 80px;
            padding: 0;
            position: sticky;
            top: 0px;
        }

        .table tbody+tbody {
            border-top: none;
        }

        .prize-table {
            width: 100%;
            /* 表格宽度为容器宽度的100% */
            height: 100vh;
            overflow-y: auto;
        }

        .prize-table .header h2 {
            background: #fff;
            width: 100%;
            font-weight: 600;
            font-size: 18px;
            color: #000000;
            height: 70px;
            display: flex;
            align-items: center;
            margin-bottom: 0;
        }

        .table-box {
            height: calc(100vh - 140px);
            overflow-y: auto;
        }

        .prize-table th,
        .prize-table td {
            text-align: center;
            vertical-align: middle;
            padding: 10px;
            height: 50px;
            /* 统一设置表头和单元格的高度 */
        }

        /* 第一列和第三列的样式 */
        .prize-table th:first-child,
        .prize-table td:first-child,
        .prize-table th:nth-child(3),
        .prize-table td:nth-child(3),
        .prize-table th:nth-child(5),
        .prize-table td:nth-child(5) {
            width: 15%;
            /* 设置第一列和第三列的宽度为15% */
        }

        /* 第四列的样式 */
        .prize-table th:nth-child(4),
        .prize-table td:nth-child(4) {
            width: 30%;
            /* 设置第四列的宽度为30% */
        }

        /* 其他列的样式（例如第二列和第五列） */
        .prize-table th:nth-child(2),
        .prize-table td:nth-child(2) {
            width: 25%;
            /* 保持第二列和第五列的宽度为20% */
        }

        .prize-table th {
            /* 如果有特定的样式只适用于表头，可以在这里添加 */
        }

        .prize-table td {
            height: 100px;
            /* 特定于单元格的高度设置 */
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            max-width: 300px;
        }

        .prize-table img {
            width: 76px;
            height: 76px;
            border-radius: 8px;
            object-fit: scale-down;
            border: 1px solid #e4e4e4;
        }

        .pagination {
            display: flex;
            justify-content: flex-end;
            margin-top: 18px;
            padding-right: 16px;
        }

        .pagination button {
            margin: 0 5px;
            /* 按钮之间的间距保持不变 */
            border-radius: 5px;
            /* 设置圆角为20像素，可以根据需要调整 */
            border: 1px solid #007bff;
            background-color: #fff;
            padding: 0px 8px;
            /* 可以添加一些内边距，使按钮看起来更饱满 */
            cursor: pointer;
            /* 将鼠标光标改为指针形状，提升用户体验 */
            font-size: 13px;
        }

        .pagination span {
            margin: 0 10px;
            font-size: 14px;
        }

        .pagination input {
            width: 80px;
            text-align: center;
        }


        .prize-table .header {
            display: flex;
            height: 70px;
        }

        .prize-table .search-box {
            padding-left: 20px;
            height: 70px;
            display: flex;
            align-items: center;
            margin-bottom: 0;
        }

        .search-box input {
            width: 300px;
            padding: 5px 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .prize-table .return-button {
            padding-left: 20px;
            height: 70px;
            display: flex;
            align-items: center;
            margin-bottom: 0;
        }

        .my-button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            background-color: #007bff;
            color: white;
            cursor: pointer;
            font-size: 14px;
            width: 80px;
            height: 40px;
        }

        /* 去除按钮点击时的黑色边框样式 */
        .my-button:focus {
            outline: none;
        }

        .my-button:active {
            background-color: #0056b3;
            /* 点击时改变的背景颜色 */
        }
    </style>
</head>

<body>
    <div class=" prize-table">
        <div class="header">
            <h2>中奖记录</h2>
            <div class="return-button">
                <button class="my-button" onclick="buttonClickHandler()">返回</button>
            </div>
        </div>
        <div class="table-box">
            <table class="table">
                <thead>
                    <tr>
                        <th>活动名称</th>
                        <th>奖品id</th>
                        <th>奖品名</th>
                        <th>奖品等级</th>
                        <th>中奖时间</th>
                    </tr>
                </thead>
                <tbody>
                <tbody id="prizeList">
                    <!-- 奖品列表将动态插入这里 -->
                </tbody>
                </tbody>
            </table>
        </div>
        <div class="pagination">
            <button class="btn-outline-primary" onclick="fetchWinningRecords(1)">首页</button>
            <button class="btn-outline-primary" onclick="previousPage()">上一页</button>
            <span>第 <input type="number" id="pageInput" min="1" value="1" /> 页</span>
            <button class="btn-outline-primary" onclick="nextPage()">下一页</button>
            <button class="btn-outline-primary" onclick="fetchWinningRecords(totalPages)">尾页</button>
        </div>
    </div>


    <script src="js/jquery.min.js"></script>
    <script>
        var userToken = localStorage.getItem("user_token");

        var currentPage = 1;
        var pageSize = 10;
        var totalPages;

        // 发送AJAX请求的函数
        function fetchWinningRecords(page) {
            // 获取当前页面的URL
            const url = window.location.href;
            // 创建URLSearchParams对象来解析URL中的查询参数部分
            const searchParams = new URLSearchParams(url.split('?').slice(1).join(''));
            // 获取名为'userId'的参数值
            const userId = searchParams.get('userId');
            const userName = searchParams.get('userName');

            // 获取 h2 元素
            const h2Element = document.querySelector('.header h2');
            // 修改 h2 元素的 innerHTML 属性来改变其内容
            h2Element.innerHTML = userName + '的中奖记录';

            console.log("userId: " + userId);
            console.log(page);
            // 如果页码小于1，则重置为1
            if (page < 1) {
                page = 1;
            }

            // 更新当前页码
            currentPage = page;

            // 构建要发送的数据对象
            var dataToSend = {
                currentPage: currentPage,
                pageSize: pageSize
            };

            // 发送AJAX请求
            $.ajax({
                url: '/user/record-list?userId=' + userId,
                type: 'get',
                data: dataToSend, // 将分页参数作为请求数据发送
                headers: {
                    // jwt
                    "user_token": userToken
                },
                dataType: 'json', // 期望从服务器接收的数据类型是JSON
                success: function (result) {
                    if (result.code != 200) {
                        alert("查询奖品列表失败！" + result.msg);
                    } else {
                        if(result.data.length == 0) {
                            alert("当前用户的中奖记录为空!");
                            return;
                        }
                        var records = result.data;
                        var prizesHtml = '';
                        // 清空现有的表格内容
                        var recordList = $('#prizeList');
                        recordList.empty();
                        records.forEach(function (records) {
                            recordList.append('<tr> ' +
                                '<td>' + records.activityName + '</td>' +
                                '<td>' + records.prizeId + '</td>' +
                                '<td>' + records.prizeName + '</td>' +
                                '<td>' + records.trie + '</td>' +
                                '<td>' + formatDate(records.winTime) + '</td>' +
                                '</tr>');
                        });
                        console.log(result.data.total + " " + pageSize)
                        // 更新分页控件的总页数
                        totalPages = Math.ceil(result.data.total / pageSize);
                        // 更新输入框的值
                        $('#pageInput').val(currentPage);
                    } // else end
                },
                error: function (err) {
                    console.log(err);
                    if (err != null && err.status == 401) {
                        alert("用户未登录, 即将跳转到登录页!");
                        // 跳转登录页
                        window.location.href = "/blogin.html";
                        window.parent.location.href = "/blogin.html";//让父页面一起跳转
                    }
                }
            }
            );
        }

        function previousPage() {
            if (currentPage > 1) {
                fetchWinningRecords(currentPage - 1);
            } else {
                alert("已经是第一页");
            }
        }

        function nextPage() {
            if (currentPage < totalPages) {
                fetchWinningRecords(currentPage + 1);
            } else {
                alert("已经是最后一页");
            }
        }

        $(document).ready(function () {
            fetchWinningRecords(1);
        });

        function formatDate(dateString) {
            // 简单的正则表达式校验，判断是否大致符合常见的日期时间字符串格式（可根据实际支持的格式进一步完善正则表达式）
            if (!/^\d{4}-\d{2}-\d{2}T?\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/.test(dateString)) {
                console.log('传入的日期时间字符串格式不符合要求');
                return null;
            }
            try {
                var date = new Date(dateString);
                var year = date.getFullYear();
                var month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份从0开始计数，所以要加1
                var day = ('0' + date.getDate()).slice(-2);
                var hour = ('0' + date.getHours()).slice(-2);
                var minute = ('0' + date.getMinutes()).slice(-2);
                var second = ('0' + date.getSeconds()).slice(-2);

                // 构建格式化的日期时间字符串
                return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
            } catch (e) {
                console.log('解析日期时间字符串出现错误：', e);
                return null;
            }
        }

        // 绑定输入框回车事件
        $('#pageInput').on('keypress', function (e) {
            if (e.key === 'Enter') {
                var page = parseInt(this.value, 10);
                if (!isNaN(page) && page >= 1 && page <= totalPages) {
                    fetchWinningRecords(page);
                }
            }
        });

        //条件搜索按钮触发
        function buttonClickHandler() {
            window.location.href = "/user-list.html";
        }

    </script>
</body>

</html>